package com.segersten.kalaha

import java.util.List
import java.util.logging.Logger
import com.segersten.kalaha.util.json.Converters
import com.google.appengine.repackaged.com.google.common.base.Flag.Integer


class BoardSessionJSON {
	
	private static Logger LOG = Logger.getLogger(getClass().getCanonicalName());

	def toJSON = { def boardSession ->
		def builder = new grails.web.JSONBuilder()
		def result = builder.build {
			sessionId = boardSession.sessionId
			player1 = [name:boardSession.player1.name, userId:boardSession.player1.userId]
			player2 = [name:boardSession.player2.name, userId:boardSession.player2.userId]
			gameType = boardSession.gameType.name()
			nextActor = boardSession.nextActor.name()
			model = boardSession.board.buckets
			lastUpdated = boardSession.lastUpdated.time
			lastUpdated2 = boardSession.lastUpdated
			round = boardSession.getLastEvent().round
			roundDuration = boardSession.roundDuration
			timestamp = new Date().getTime();
		}
		return result.toString()
	}

	def toJSON2 = { def finishedGame ->
		def builder = new grails.web.JSONBuilder()
		def result = builder.build {
			sessionId = finishedGame.sessionId
			player1 = [name:finishedGame.player1Name, userId:finishedGame.player1]
			player2 = [name:finishedGame.player2Name, userId:finishedGame.player2]
			gameType = finishedGame.gameType
			nextActor = Actor.NONE.name()
			model = calculateKalahaModel(finishedGame.endState)
			lastUpdated = finishedGame.finishedTime
			round = -1
			state = finishedGame.getFinishedReason()
			winner = finishedGame.getWinner()
			player1score = finishedGame.player1Points
			player2score = finishedGame.player2Points
			timestamp = new Date().getTime();
		}
		return result.toString()
	}
	
	def calculateKalahaModel = { String model ->
		return Converters.stringToIntArray(model.substring(1, model.length()-1))
	}
	
}
